#include "XQueryPipelineElements.h"

#include <QFile>
#include <QBuffer>
#include <QStringList>
#include <QtDebug>
#include <QXmlFormatter>

XQueryProcessor::XQueryProcessor()
{
}

XQueryProcessor::~XQueryProcessor()
{
}

void XQueryProcessor::setup(const QDomNode& setupDescription)
{
}
    
void XQueryProcessor::process()
{
    qDebug() << "evaluating: " << queryPath;
    evaluateQuery();
}

void XQueryProcessor::evaluateQuery()
{
    // load the parent result inta a buffer
    const QByteArray& inputByteArray = parent->result();
    QBuffer inputBuffer;
    inputBuffer.setData(inputByteArray);
    inputBuffer.open(QIODevice::ReadOnly);
    
    // create the XQuery with a variable to the parent result
    QXmlQuery query;
    query.bindVariable("inputDocument", &inputBuffer);
    
    // load the XQuery source from the file
    QFile querySource(queryPath);
    querySource.open(QIODevice::ReadOnly);
    QTextStream queryTextStream(&querySource);
    query.setQuery(queryTextStream.readAll());
    
    // eveluate the XQuery and convert the results to a QDomDocument
    if (query.isValid()) {
        // create an output device to collect the results
        QBuffer resultsBuffer(&buffer);
        resultsBuffer.open(QIODevice::ReadWrite);
        
        // create an XML formatter to interface with the XQuery engine
        QXmlFormatter formatter(query, &resultsBuffer);

        // evaluate the query
        if (!query.evaluateTo(&formatter))
            qDebug() << "error while evaluating query";
        else
            resultsBuffer.close();
    }
    else {
        qDebug() << "query is not valid";
    }
}
